<template>
  <div class="video-div"   >
    <div class="video-title" v-if="hasTitle">
      <div class="video-title-label">{{ props.name }}</div>
      <div class="video-title-action" v-if="props.hasAction">
        <a class="action-a" @click="onStartNVRDownload(false)">下载</a>
        <a class="action-a" v-show="props.timeRang" @click="onStartNVRDownload(true)">切片</a>
        <!-- <a class="action-a"   @click="fullscreen">全屏</a> -->
      </div>
    </div>
    <div class="video-content" :id="props.rootId" v-resize="onResize">
      <!-- <div class="video-fullscreen">
                <FullscreenOutlined :style="{color:'red' ,fontSize:'24px',cursor:'pointer'}" @click="fullscreen" />
      </div> -->
      <div class="video-open" v-if="props.cameraPlaybackObj && !started">
        <PlayCircleOutlined :style="{ color: '#fff', fontSize: '44px', cursor: 'pointer' }" @click="startPreview" />
      </div>
      <div class="video-process" v-show="isCuting">
        下载进度： {{ processText }}
      </div>
      <div class="video-scroll-process" v-if="started">
        <CProgress @percentChange="percentChange" :history="props.history" v-model:percent="percent" :fontSize="iconFontSize"  v-model:isStart="started" @stopPlay="stopPlay" @exitFullScreen="exitfull" @fullscreen="fullscreen"  @startPlay="startPlay" :violationTime="timestampVideo"
         :width="width">
        </CProgress>
      </div>
      <video :id="props.videoId" class="video-h5"></video>
      <canvas :id="props.canvasId" class="canvas-h5"></canvas>
    </div>

  </div>

</template>
<script lang="ts" setup>

import { defineComponent, defineProps, onMounted, onUnmounted, ref } from 'vue'
import { FullscreenOutlined, PlayCircleOutlined } from '@ant-design/icons-vue'
import { Item } from 'ant-design-vue/es/menu';
import CProgress from './CProgress.vue'
import dayjs from 'dayjs';
let targetIpPort = ref("");
let player = null;
let started = ref(false)
let isCuting = false;  //是否正在进行视频裁剪
let processText = ref('')
let cutPlayer = null;
let timestampVideo = ref('');
let percent = ref(0);
let width = ref(0);
let isStart = ref(false);
let iconFontSize = ref('22px');
let isScreen = ref(false)
const props = defineProps({
  name: {
    type: String,
    default: ''
  },
  videoId: {
    type: String,
    default: ''
  },
  canvasId: {
    type: String,
    default: ''
  },
  caramObj: {
    type: Object,
    default: {}
  },
  deviceObj: {
    type: Object,
    default: {}
  },
  hasAction: {
    type: Boolean,
    default: false
  },
  hasTitle: {
    type: Boolean,
    default: true
  },
  startTime: {
    type: String,
    default: ""
  },
  cameraPlaybackObj: {
    type: Object,
    default: null
  },
  OpeningChannel: {//通道号
    type: String,
    default: ''
  },
  timeRang: {
    type: Number,
    defailt: 0
  },
  // width:{
  //   type:Number,
  //   defailt:0
  // },
  violationTime: {
    type: String,
    default: '',//视频起点
  },
  history: {
    type: Boolean,
    default: false
  },
  rootId:{
    type: String,
    default: 'videoRootId',//视频起点
  }

})
let WebCaps = null;  //webCapsConfig文件转存变量

/**
 * 全屏
 */
const fullscreen = () => {
  let docElm = window.top.document.documentElement;
  console.log("quan::",docElm);
  
  if (docElm.requestFullScreen) {
    docElm.requestFullScreen();
  } else if (docElm.mozRequestFullScreen) {
    docElm.mozRequestFullScreen();
  } else if (docElm.webkitRequestFullScreen) {
    docElm.webkitRequestFullScreen();
  } else if (docElm.msRequestFullscreen) {
    docElm.msRequestFullscreen();
  }
  iconFontSize.value = '28px';
  handleFullscreen(true);
}

// 当元素宽高发生变化时，触发下面的方法
const onResize = (dom) => {
  if (dom?.width > 0) {
    width.value = dom.width - 130;
  }
}
const percentChange = (e) => {
  let startTimeUnix = dayjs(props.cameraPlaybackObj.StartTime).unix()
  let endTimeUnix = dayjs(props.cameraPlaybackObj.EndTime).unix()
  // let p = (e.timestamp - startTimeUnix /endTimeUnix - startTimeUnix) / 100;
  let p = e / 100 * (endTimeUnix - startTimeUnix)//秒数
  
  player && player.playByTime(p);
}
/**
 * @description 处理全屏开关时的窗口大小
 * @param {boolean} bool 是否要全屏
 */
function handleFullscreen(bool) {
  if (bool) {
    let wrap = {
      position: 'fixed',
      left: 0,
      top: 0,
      width: '100vw',
      height: '100vh',
      'z-index':999999999,
      overflow: 'visible'
    }
    isScreen.value = true;
    setStyle(document.getElementById(props.rootId), wrap);
  } else {
    let wrap = {
      position: 'relative',
      overflow: 'hidden',
      width: '100%',
      'z-index':0,
      height: '100%',
    }
    console.log("rootId",document.getElementById(props.rootId));
    
    setStyle(document.getElementById(props.rootId), wrap);
  }
}
/**
 * @description 设置样式
 * @param {object} obj dom元素
 * @param {*} json css样式
 */
function setStyle(obj, json) {
  if(obj){
    for (let i in json) {
      obj.style[i] = json[i];
    }
  }
  
}
/**
 * 初始化
 */
const init = () => {
  let target = props.deviceObj.ip + ':' + props.deviceObj.port;
  var options = {
    wsURL: `ws://${target}/rtspoverwebsocket`,
    rtspURL: `rtsp://${target}/cam/realmonitor?channel=${props.OpeningChannel}&subtype=0&proto=Private3`,
    username: props.deviceObj.username,
    password: props.deviceObj.password,
    realm: window.RPC.realm, //设备登录返回的realm
  };
  var videoplayerObj = document.getElementById(props.videoId);
  var canvasplayerObj = document.getElementById(props.canvasId);
  player = new window.PlayerControl(options);
  player.on('DecodeStart', function (e) {
    if (e.decodeMode === 'video') {
      document.getElementById(props.videoId).style.display = '';
      document.getElementById(props.canvasId).style.display = 'none';
    } else {
      document.getElementById(props.videoId).style.display = 'none';
      document.getElementById(props.canvasId).style.display = '';
    }
  });
  
  player.on('WorkerReady', function () {
    //当文件准备完成后，开始拉流。
    player.connect();
  });
  player.init(canvasplayerObj, videoplayerObj);
  started.value = true;
  console.log(" started.value==", started.value);
  

}
const stopPlay = ()=>{
  if(player){
    player.pause();
    started.value = false;
  }
}
const startPlay = ()=>{
  if(player){
    player.play()
    started.value = true;
  }
}
/**
 * @description 停止预览
 */
const onStopPreview = () => {
  if (player) {
    player.stop();
    player.close();
    player = null;
    started.value = false;
  }
  document.querySelectorAll(`[id^=${props.videoId}]`).forEach(item => {
    if (item.style.display === '') {
      item.style.display = 'none';
    }
  });
  document.querySelectorAll(`[id^=${props.canvasId}]`).forEach(item => {
    if (item.style.display === '') {
      item.style.display = 'none';
    }
  });
}
const startPreview = () => {
  onPreview(true, props.cameraPlaybackObj.FilePath, props.cameraPlaybackObj.playbackIndex)
}
/**
 * @description 开始下载录像
 * @param {object} item 录像信息
 */
const onStartNVRDownload = (cut) => {

  let firstTime = 0;

  let ip = props.deviceObj.ip;
  let port = props.deviceObj.port;
  let username = props.deviceObj.username;
  let password = props.deviceObj.password;
  let url = props.cameraPlaybackObj.FilePath;
  let _rtspURL = 'rtsp://' + ip + ':' + port + '/' + url;
  let optionsRecord = {
    wsURL: 'ws://' + ip + ':' + port + '/rtspoverwebsocket',
    rtspURL: _rtspURL,
    username: username,
    password: password,
    isPrivateProtocol: false,
    realm: RPC.realm,
    speed: 16,
    playback: true,
    isDownLoad: true
  }
  if (cut) {
    optionsRecord.range = props.timeRang //视频裁剪时间与视频的StartTime时间差值
  }
  cutPlayer = new window.PlayerControl(optionsRecord);

  cutPlayer.on('FileOver', function () {
    cutPlayer.startCut(false);

  });
  cutPlayer.on('UpdateTimeStamp', function (e) {
    let s1 = new Date(props.cameraPlaybackObj.StartTime).getTime() / 1000;
    let e1 = new Date(props.cameraPlaybackObj.EndTime).getTime() / 1000;
    if (firstTime === 0) {
      firstTime = e.timestamp;
    }


    let process = parseInt(((e.timestamp - firstTime) / (e1 - s1)) * 100);
    processText.value = (process > 100 ? 100 : process) + '%';
    if ((e.timestamp >= firstTime) && !isCuting) {
      cutPlayer.startCut(true);
      isCuting = true;
    }
    if ((e.timestamp >= e1 || process >= 100) && isCuting) {
      cutPlayer.startCut(false);
      isCuting = false;
    }
  });
  var videoplayerObj = document.getElementById(props.videoId);
  var canvasplayerObj = document.getElementById(props.canvasId);
  cutPlayer.init(canvasplayerObj, videoplayerObj);
  cutPlayer.connect(true);
}
//   /**
//   * @description 针对回放视频的，视频裁剪
//   */
//   const  onStartCut = () => {

//      let cutPlayer = null;
//      let _rtspURL =  'rtsp://'+ ip +':' + port + '/' + url;
//      let cutStartTime = $('#h5_cutStartTime').value;
//      let s = new Date(cutStartTime.replace('T', ' ')).getTime();
//      let startTime = new Date(recordArr[_cutIndex].StartTime).getTime();
//      let range1 = (s - startTime)/1000;
//      let firstTime=0;
//      let optionsRecord = {
//          wsURL: 'ws://'+ ip +':' + port + '/rtspoverwebsocket',
//          rtspURL: _rtspURL,
//          username: username,
//          password: password,
//          isPrivateProtocol: false, //是否私有协议，默认false
//          realm: RPC.realm, //登录返回的设备Realm值
//          speed: 16, //倍速拉流，16倍速
//          playback: true, //是都回放
//          isDownLoad:true,
//          range: range1 //视频裁剪时间与视频的StartTime时间差值
//      }
//      cutPlayer = new PlayerControl(optionsRecord);
//      cutPlayer.on('FileOver',function(){
//          console.log('File Over');
//          cutPlayer.startCut(false);
//          isCuting = false;	
//          $('#h5_cut_process').innerText = '100%';
//      });
//      cutPlayer.on('UpdateTimeStamp', function (e) {
//          let cutStartTime1 = $('#h5_cutStartTime').value;
//          let cutEndTime1 = $('#h5_cutEndTime').value;
//          if (firstTime === 0) {
//              firstTime = e.timestamp;
//          }
//          let s1 = new Date(cutStartTime1.replace('T', ' ')).getTime() / 1000;
//          let e1 = new Date(cutEndTime1.replace('T', ' ')).getTime() / 1000;
//          let process = parseInt(((e.timestamp-firstTime) / (e1 - s1)) * 100);
//          // console.log(new Date(e.timestamp * 1000));
//          $('#h5_cut_process').innerText = (process > 100 ? 100 : process)  + '%';
//          if((e.timestamp >=  s1) && !isCuting) {
//              cutPlayer.startCut(true);
//              isCuting = true;
//          }
//          if((e.timestamp >= e1 ) && isCuting) {
//              cutPlayer.startCut(false);
//              isCuting = false;
//              $('#h5_cut_process').innerText = '100%';
//          }
//      });
//      cutPlayer.init($canvas, $video);
//      cutPlayer.connect(true);
//      cutInstance[WndIndex] = cutPlayer;
//  }

/**
 * @description 预览
 * @param {boolean} isPlayback 是否是回放
 * @param {string} url 回放视频的url
 * @param {number} playbackIndex 回放视频的索引
 * @param {boolean} isChangeStream 是否是切换码流导致的重新拉流
 */
const onPreview = (isPlayback, url, playbackIndex, isChangeStream) => {
  // if(playerInstance[WndIndex] && onlineChannel.indexOf(channel) > -1 && !isChangeStream){
  //     alert('通道' + (channel + 1) + '已存在！');
  //     return;
  // }
  if(player){
    player.play();
    started.value = true;
    return false;
  }
  onStopPreview();
  let curChannel = props.cameraPlaybackObj.Channel + 1; //无插件通道号从1开始
  let ip = props.deviceObj.ip;
  let port = props.deviceObj.port;
  let username = props.deviceObj.username;
  let password = props.deviceObj.password;
  let options = {
    wsURL: 'ws://' + ip + ':' + port + '/rtspoverwebsocket',
    rtspURL: 'rtsp://' + ip + ':' + port + '/' + url,
    username: username,
    password: password,
    lessRateCanvas: true,
    playback: isPlayback,
    isPrivateProtocol: false,
    realm: window.RPC.realm, //设备登录返回的realm
    playbackIndex: playbackIndex,
    h265AccelerationEnabled: true, // 硬解码是否开启，默认不开启
  };
  player = new window.PlayerControl(options);
  player.on('MSEResolutionChanged', function (e) {
    console.log(e)
  });
  player.on('PlayStart', function (e) {
    // document.getElementById(props.videoId).style.display = 'none';
    if (props.cameraPlaybackObj && props.cameraPlaybackObj?.time >= 0) {
      player.playByTime(props.cameraPlaybackObj.time);
    }
  });
  player.on('DecodeStart', function (e) {
    if (e.decodeMode === 'video') {
      document.getElementById(props.videoId).style.display = '';
      document.getElementById(props.canvasId).style.display = 'none';
    } else {
      document.getElementById(props.videoId).style.display = 'none';
      document.getElementById(props.canvasId).style.display = '';
    }

  });
  player.on('UpdateCanvas', function (e) {
    if (dayjs.unix(e.timestamp).format('YYYY-MM-DD HH:mm:ss') != props.cameraPlaybackObj.StartTime && props.cameraPlaybackObj?.time >= 0) {
      timestampVideo.value = dayjs.unix(e.timestamp).format('HH:mm:ss')

      let startTimeUnix = dayjs(props.cameraPlaybackObj.StartTime).unix()
      let endTimeUnix = dayjs(props.cameraPlaybackObj.EndTime).unix()
      let p = ((e.timestamp - startTimeUnix) / (endTimeUnix - startTimeUnix)) * 100;
      percent.value = p
    }

  });
  player.on('GetTotalTime', function (e) {

  });
  player.on('GetFrameRate', function (e) {
    console.log('GetFrameRate: ' + e)
  });
  player.on('FrameTypeChange', function (e) {
    console.log('FrameTypeChange: ' + e)
  });
  player.on('Error', function (e) {
    console.log('Error: ' + JSON.stringify(e))
  });
  player.on('IvsDraw', function (e) {
    //console.log('IvsDraw: ' + JSON.stringify(e))
  });
  player.on('FileOver', function () {
    onStopPreview();
  });
  player.on('WorkerReady', function () {
    player.connect();
  });
  var videoplayerObj = document.getElementById(props.videoId);
  var canvasplayerObj = document.getElementById(props.canvasId);
  player.init(canvasplayerObj, videoplayerObj);
  started.value = true;

}
/**
 * @description 注销
 */
const onLogout = () => {
  /**
   * RPC.Global.logout 注销接口
   * @returns {Promise}
   */
  try {
    console.log("子组件销毁");

    // window.RPC.Global.logout().then(function () {
    if (player) {
      player.stop();
      player.close();
      player = null;
    }
    document.querySelectorAll('[id^=videoId]').forEach(item => {
      if (item.style.display === '') {
        item.style.display = 'none';
      }
    });
    document.querySelectorAll('[id^=canvasId]').forEach(item => {
      if (item.style.display === '') {
        item.style.display = 'none';
      }
    });

    if (cutPlayer) {
      cutPlayer.stop();
      cutPlayer.close();
      cutPlayer.startCut(false, true);
      isCuting = false;
    }

    // });
  } catch (e) {

  }

}
onMounted(() => {
  if (!props.cameraPlaybackObj && props.OpeningChannel) {
    init()
  } else {
    if (props.cameraPlaybackObj?.violationTime) {
      let time = dayjs(props.cameraPlaybackObj?.violationTime).unix()

      timestampVideo.value = dayjs.unix(time).format('HH:mm:ss');
      let startTimeUnix = dayjs(props.cameraPlaybackObj.StartTime).unix()
      let endTimeUnix = dayjs(props.cameraPlaybackObj.EndTime).unix()
      let p = ((time - startTimeUnix) / (endTimeUnix - startTimeUnix)) * 100;
      percent.value = Math.floor(p)
    }
  }
  ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'msfullscreenchange'].forEach((item, index) => {
        document.addEventListener(item, fullscreenchange, false);
    });

})
/**
 * @description 获取全屏状态
 */
 function getFull() {
  if (document.fullscreenElement ||
            document.mozFullScreenElement ||
            document.webkitFullscreenElement ||
            document.msFullscreenElement) {
            // 当前处于全屏状态
            return true;
        } else {
            // 当前非全屏状态
            return false;
        }
}
/**
 * @description 全屏状态改变的回调事件
 */
 function fullscreenchange() {
  console.log("全屏状态：：",getFull());
  
    if (getFull()) {
        return;
    } else {
        iconFontSize.value = '22px';
        exitfullScreen();
    }
}
const exitfull =()=>{
  isScreen.value = false;
  iconFontSize.value = '22px';
  exitfullScreen();
}
/**
 * @description 退出全屏
 */
 function exitfullScreen() {
  if (document.exitFullscreen) {  
            document.exitFullscreen();  
        } else if (document.mozCancelFullScreen) { /* Firefox */  
            document.mozCancelFullScreen();  
        } else if (document.webkitExitFullscreen) { /* Chrome, Safari and Opera */  
            document.webkitExitFullscreen();  
        } else if (document.msExitFullscreen) { /* IE/Edge */  
            document.msExitFullscreen();  
        }  
    handleFullscreen(false);
}
onUnmounted(() => {
  console.log("VideoContent onUnmounted")
  onLogout()
})

</script>
<style lang="less" scoped>
.video-div {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  .video-title {
    width: 100%;
    height: 30px;
    display: flex;

    .video-title-label {
      flex: 1;
    }

    .video-title-action {
      margin-left: auto;

      .action-a {
        margin-left: 10px;
      }
    }
  }

  .video-content {
    background-color: #000;
    flex: 1;
    display: flex;
    flex-shrink: 0;
    overflow: hidden;
    position: relative;

    .video-open {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      z-index: 2;
    }

    .video-process {
      position: absolute;
      right: 2%;
      top: 2%;
      color: red;
      z-index: 100000;
    }

    .video-scroll-process {
      position: absolute;
      width: 100%;
      padding: 20px;
      left: 0%;
      bottom: 0%;
      color: red;
      z-index: 2;
    }

    .video-fullscreen {
      position: absolute;
      right: 10px;
      top: 10px;
    }

    .video-h5,
    .canvas-h5 {
      flex: 1;
    }
  }

}
</style>